package com.fanxl.flink.project.app;

import com.alibaba.fastjson.JSON;
import com.fanxl.flink.project.domain.Access;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Objects;

/**
 * @description: 按操作系统维度统计新老用户
 * @author: fanxiaole
 * @date: 2022/3/20 17:00
 */
public class OsUserCntAppV2 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> dataStreamSource = env.readTextFile("data/access.json");
        SingleOutputStreamOperator<Access> cleanStream = dataStreamSource.map(new MapFunction<String, Access>() {
            @Override
            public Access map(String value) throws Exception {
                try {
                    return JSON.parseObject(value, Access.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        })
        .filter(Objects::nonNull)
        .filter(new FilterFunction<Access>() {
            @Override
            public boolean filter(Access value) throws Exception {
                return "startup".equals(value.getEvent());
            }
        });
        // 按操作系统 新老用户维度 进行计数
        cleanStream.map(new MapFunction<Access, Tuple3<String, Integer, Integer>>() {
            @Override
            public Tuple3<String, Integer, Integer> map(Access value) throws Exception {
                return Tuple3.of(value.os, value.nu, 1);
            }
        })
        // 按操作系统 新老用户维度进行分组
        .keyBy(new KeySelector<Tuple3<String, Integer, Integer>, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> getKey(Tuple3<String, Integer, Integer> value) throws Exception {
                return Tuple2.of(value.f0, value.f1);
            }
        }).sum(2).print();
        env.execute("OsUserCntAppV2");
    }

}
